#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
打包脚本 - 将若依框架修改器打包成DMG
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def run_command(cmd, cwd=None):
    """运行命令"""
    print(f"执行命令: {cmd}")
    result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"错误: {result.stderr}")
        return False
    print(f"成功: {result.stdout}")
    return True

def install_pyinstaller():
    """安装PyInstaller"""
    print("正在安装PyInstaller...")
    return run_command("pip install pyinstaller")

def create_spec_file():
    """创建PyInstaller配置文件"""
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['run.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('conf', 'conf'),
        ('img', 'img'),
        ('libs', 'libs'),
        ('ui', 'ui'),
        ('core', 'core'),
        ('spider', 'spider'),
        ('utils', 'utils'),
        ('constant', 'constant'),
    ],
    hiddenimports=[
        'wx',
        'wx.adv',
        'loguru',
        'requests',
        'pyperclip',
        'bs4',
        'chardet',
        'Crypto',
        'ui.main.main',
        'ui.config.config',
        'ui.config.templateConfig',
        'ui.about.about',
        'ui.reward.reward',
        'ui.druidencrypt.druidencrypt',
        'ui.filedel.filedel',
        'ui.manual.manual',
        'core.ruoyi',
        'core.ruoyicloud',
        'core.ruoyifast',
        'core.ruoyivue',
        'spider.upgradespider',
        'utils.configini',
        'utils.path',
        'utils.aescrypt',
        'constant.constant',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name='若依框架修改器',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='bin/mac/icon.icns',
)

coll = COLLECT(
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name='若依框架修改器',
)

app = BUNDLE(
    coll,
    name='若依框架修改器.app',
    icon='bin/mac/icon.icns',
    bundle_identifier='com.ruoyi.mt',
    info_plist={
        'CFBundleName': '若依框架修改器',
        'CFBundleDisplayName': '若依框架修改器',
        'CFBundleVersion': '4.7.7.20230425',
        'CFBundleShortVersionString': '4.7.7',
        'NSHighResolutionCapable': True,
        'LSMinimumSystemVersion': '10.15.0',
    },
)
'''
    
    with open('若依框架修改器.spec', 'w', encoding='utf-8') as f:
        f.write(spec_content)
    print("已创建PyInstaller配置文件")

def build_app():
    """构建应用程序"""
    print("正在构建应用程序...")
    return run_command("pyinstaller 若依框架修改器.spec")

def create_dmg():
    """创建DMG文件"""
    print("正在创建DMG文件...")
    
    # 创建临时目录
    dmg_dir = "DMG_Temp"
    if os.path.exists(dmg_dir):
        shutil.rmtree(dmg_dir)
    os.makedirs(dmg_dir)
    
    # 复制应用程序到临时目录
    app_path = "dist/若依框架修改器.app"
    if os.path.exists(app_path):
        shutil.copytree(app_path, f"{dmg_dir}/若依框架修改器.app")
    
    # 创建Applications的软链接
    os.symlink("/Applications", f"{dmg_dir}/Applications")
    
    # 创建DMG
    dmg_name = "若依框架修改器_v4.7.7.dmg"
    if os.path.exists(dmg_name):
        os.remove(dmg_name)
    
    # 使用hdiutil创建DMG
    cmd = f'hdiutil create -volname "若依框架修改器" -srcfolder {dmg_dir} -ov -format UDZO {dmg_name}'
    success = run_command(cmd)
    
    # 清理临时目录
    shutil.rmtree(dmg_dir)
    
    if success:
        print(f"DMG文件已创建: {dmg_name}")
        return True
    return False

def main():
    """主函数"""
    print("=== 若依框架修改器 DMG打包工具 ===")
    print()
    
    # 检查Python环境
    if not run_command("python3 --version"):
        print("错误: 无法检测到Python3")
        return
    
    # 安装PyInstaller
    if not install_pyinstaller():
        print("错误: 安装PyInstaller失败")
        return
    
    # 创建spec文件
    create_spec_file()
    
    # 构建应用
    if not build_app():
        print("错误: 构建应用程序失败")
        return
    
    # 创建DMG
    if create_dmg():
        print("\n✅ 打包完成！")
        print("DMG文件已生成在当前目录")
    else:
        print("\n❌ 打包失败！")

if __name__ == "__main__":
    main() 